package com.xy.webadmin.app.schdule;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xy.common.core.upload.BaseUpDownloader;
import com.xy.common.core.upload.UpDownloaderFactory;
import com.xy.common.core.upload.UploadStoreTypeEnum;
import com.xy.webadmin.app.model.EmailAttachment;
import com.xy.webadmin.app.model.userEmail.UserEmailConfig;
import com.xy.webadmin.app.model.userEmail.UserEmailReceivedInfo;
import com.xy.webadmin.app.service.UserEmailConfigService;
import com.xy.webadmin.app.service.UserEmailReceivedInfoService;
import com.xy.webadmin.common.email.util.EmailPOP3Util;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.xy.application.common.constant.YesOrNo.YES;

@Slf4j
@Component
public class UserEmailPOP3Schedule {

    @Autowired
    private UserEmailConfigService userEmailConfigService;

    @Resource
    private UserEmailReceivedInfoService userEmailReceivedInfoService;

    @Resource
    private UpDownloaderFactory upDownloaderFactory;

    @Resource
    private jakarta.servlet.http.HttpServletRequest request;

    @Value("${common-ext.uploadFileBaseDir:./zz-resource/upload-files/commonext}")
    private String uploadFileBaseDir;

    /**
     *
     */
//    @Scheduled(cron = "0/5 * * * * ?")
    public void checkEmails() {
        log.info("开始执行邮件检查任务");
        // 获取所有未删除的邮箱配置
        List<UserEmailConfig> activeConfigs = userEmailConfigService.list(new LambdaQueryWrapper<UserEmailConfig>()
                .isNotNull(UserEmailConfig::getEmail)
                .isNotNull(UserEmailConfig::getAuthCode)
                .isNotNull(UserEmailConfig::getReceiveHost)
                .isNotNull(UserEmailConfig::getReceivePort)
                .eq(UserEmailConfig::getIsActive, YES)
        );
        for (UserEmailConfig config : activeConfigs) {
            try {
                fetchEmails(config);
            } catch (Exception e) {
                log.error("处理邮箱 {} 时发生错误: {}", config.getEmail(), e.getMessage(), e);
            }
        }
    }

    /**
     * 获取指定邮箱的邮件
     */
    private void fetchEmails(UserEmailConfig config) throws MessagingException {
        log.info("开始获取邮箱 {} 的邮件", config.getEmail());

        Store store = null;
        try {
            // 连接到邮件服务器
            store = EmailPOP3Util.connectToEmailServer(config);
            
            // 获取今天的邮件
            List<Message> todayMessages = EmailPOP3Util.getTodayMessages(store);
            
            // 找到这个人的Id
            UserEmailConfig emailConfig = userEmailConfigService.getOne(new LambdaQueryWrapper<UserEmailConfig>()
                    .eq(UserEmailConfig::getEmail, config.getEmail()));
            Long sysUserId = emailConfig.getSysUserId();

            for (Message message : todayMessages) {
                String messageId;

                try {
                    //获取邮件的唯一ID
                    String[] header = message.getHeader("Message-ID");
                    if (header != null) {
                        for (String s : header) {
                            log.info("邮件ID: {}", s);
                        }
                    }
                    if (header != null) {
                        //查找是否已经处理了这个邮件
                        messageId = header[0];
                        UserEmailReceivedInfo one = userEmailReceivedInfoService.getOne(new LambdaQueryWrapper<UserEmailReceivedInfo>()
                                .eq(UserEmailReceivedInfo::getEmailId, messageId)
                                .eq(UserEmailReceivedInfo::getSysUserId, sysUserId)
                        );
                        if (one != null) {
                            continue;
                        }
                    } else {
                        continue;
                    }

                    UserEmailReceivedInfo needSaveInfo = new UserEmailReceivedInfo();
                    needSaveInfo.setSysUserId(sysUserId);
                    needSaveInfo.setEmailId(messageId);
                    needSaveInfo.setReceiveTime(LocalDateTime.now());
                    needSaveInfo.setCompanyId(config.getCompanyId());

                    // 获取完整的邮件内容
                    Object content = message.getContent();

                    //邮件标题
                    String subject = message.getSubject();
                    needSaveInfo.setSubject(subject);

                    //发件人
                    String sender = EmailPOP3Util.getSenderAddress(message);
                    needSaveInfo.setSender(sender);
                    log.info("发件人: {}", sender);

                    //发送时间
                    Date sentDate = message.getSentDate();
                    needSaveInfo.setSendTime(DateUtil.toLocalDateTime(sentDate));

                    // 处理邮件内容
                    String emailContent = EmailPOP3Util.processEmailContent(message, needSaveInfo);
                    needSaveInfo.setContent(emailContent);

                    // 处理附件
                    if (content instanceof Multipart) {
                        Multipart multipart = (Multipart) content;
                        BaseUpDownloader upDownloader = upDownloaderFactory.get(UploadStoreTypeEnum.LOCAL_SYSTEM);
                        List<EmailAttachment> attachments = EmailPOP3Util.processAttachments(multipart, upDownloader, uploadFileBaseDir);
                        
                        if (!attachments.isEmpty()) {
                            needSaveInfo.setHasAttachment(YES);
                            List<String> attachmentsUrl = new ArrayList<>();
                            for (EmailAttachment attachment : attachments) {
                                attachmentsUrl.add(attachment.getUrl());
                            }
                            System.out.println("附件连接:" + attachmentsUrl);
                            needSaveInfo.setAttachmentUrl("[" + String.join(",", attachmentsUrl) + "]");
                        }
                    }

                    // 保存邮件内容
                    userEmailReceivedInfoService.save(needSaveInfo);

                } catch (Exception e) {
                    log.error("处理邮件时发生错误: {}", e.getMessage(), e);
                }
            }

            // 关闭连接
            if (store != null) {
                store.close();
            }
            log.info("完成邮箱 {} 的邮件处理", config.getEmail());

        } catch (Exception e) {
            log.error("处理邮箱 {} 时发生错误: {}", config.getEmail(), e.getMessage(), e);
            throw e;
        }
    }
}
